import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'

import {ToastPlugin, LoadingPlugin} from 'vux'
Vue.use(ToastPlugin)
Vue.use(LoadingPlugin)

import store from '../store'

const env = process.env.NODE_ENV === 'development'
const baseURL = (env ? '/api/' : store.state.domain) + 'interface.php?act='

const instance = axios.create({
  timeout: 60000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

const loadingHide = () => {
  
}

Vue.$vux.loadingArr = []

instance.interceptors.request.use(config => {
  if(config.url.indexOf('IMheartbeat') != -1) Vue.$vux.loading.hide()
  else Vue.$vux.loading.show()
  Vue.$vux.loadingArr.push(new Date().getTime())
  if(store.state.token) {
    config.headers.common['Authorization'] = store.state.token
    config.headers.common['userId'] = store.state.userId
  }
  return config
}, error => {
  Vue.$vux.loading.hide()
  Vue.$vux.loadingArr = []
  return Promise.reject(error)
})

instance.interceptors.response.use(response => {
  if(Vue.$vux.loadingArr.length == 1) {
    Vue.$vux.loading.hide()
  }
  Vue.$vux.loadingArr.pop()
  if(response.data.code && response.data.code != '200') {
    Vue.$vux.toast.show({
      type: 'text',
      text: '<span style="padding: 0 1em;">' + (response.data.msg || '系统维护中，请稍后重试！') + '</span>',
      width: 'max-content',
    })
  }
  return response
}, error => {
  Vue.$vux.loading.hide()
  Vue.$vux.loadingArr = []
  // alert(error)
  Vue.$vux.toast.show({
    type: 'text',
    text: '<span style="padding: 0 1em;">网络出错，请稍后重试！</span>',
    width: 'max-content',
  })
  return Promise.reject(error)
})

export default {
  fetchGet (url, params = {}) {
    return new Promise((resolve, reject) => {
      // if(url == 'IMheartbeat') Vue.$vux.loading.hide()
      instance.get(baseURL + url, {params}).then(res => {
        if(url == 'login') resolve(res)
        else resolve(res.data)
      }).catch(error => {
        reject && reject(error)
      })
    })
  },
  fetchPost (url, params = {}) {
    return new Promise((resolve, reject) => {
      instance.post(baseURL + url, qs.stringify(params)).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject && reject(error)
      })
    })
  }
}
